<template>
  <div class="profile-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本信息" name="profile">
        <el-form ref="profileFormRef" :model="profileForm" :rules="profileRules" label-width="80px" class="profile-form">
          <el-form-item label="用户昵称" prop="realName">
            <el-input v-model="profileForm.realName" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="profileForm.phone" />
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="profileForm.email" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitProfileForm">保存</el-button>
            <el-button @click="resetProfileForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="修改密码" name="password">
        <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="80px" class="password-form">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input v-model="passwordForm.oldPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitPasswordForm">修改密码</el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="上传头像" name="avatar">
        <div class="avatar-upload">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="false"
            ref="uploadRef"
            :on-change="handleChange"
          >
            <img v-if="userStore.userInfo.avatar" :src="fullAvatarUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="tip">点击选择头像，然后点击上传按钮</div>
          <el-button type="primary" @click="submitUpload" :disabled="!fileToUpload" style="margin-top: 10px;">上传到服务器</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules, UploadProps, UploadRawFile, UploadFile } from 'element-plus'
import { useUserStore } from '@/store/user'
import { getInfo, updateProfile, updatePassword, uploadAvatar } from '@/api/user'
import { Plus } from '@element-plus/icons-vue'

const emit = defineEmits(['close', 'success'])
const userStore = useUserStore()
const activeTab = ref('profile')

// 个人信息表单
const profileFormRef = ref<FormInstance>()
const profileForm = reactive({
  realName: '',
  phone: '',
  email: '',
})
const profileRules = reactive<FormRules>({
  realName: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 密码修改表单
const passwordFormRef = ref<FormInstance>()
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})
const passwordRules = reactive<FormRules>({
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 头像上传
const uploadRef = ref()
const fileToUpload = ref<File | null>(null)

const fullAvatarUrl = computed(() => {
  return userStore.userInfo.avatar ? `${import.meta.env.VITE_BASE_API}${userStore.userInfo.avatar}` : '';
});

// 文件选择改变时触发
const handleChange: UploadProps['onChange'] = (uploadFile: UploadFile) => {
  fileToUpload.value = uploadFile.raw || null;
}

// 手动上传到服务器
const submitUpload = async () => {
  if (!fileToUpload.value) {
    ElMessage.warning('请先选择要上传的头像图片');
    return;
  }

  console.log('准备上传文件:', fileToUpload.value);
  const valid = beforeAvatarUpload(fileToUpload.value); // 再次执行预校验
  if (!valid) {
    fileToUpload.value = null; // 清除文件，避免再次尝试上传无效文件
    if (uploadRef.value) {
      uploadRef.value.clearFiles(); // 清除el-upload的内部文件列表
    }
    return;
  }

  try {
    const res = await uploadAvatar(fileToUpload.value);
    handleAvatarSuccess(res, fileToUpload.value); // 调用成功处理函数
  } catch (error: any) {
    ElMessage.error(error.msg || '头像上传失败');
  } finally {
    fileToUpload.value = null; // 上传完成后清空文件
    if (uploadRef.value) {
      uploadRef.value.clearFiles(); // 清除el-upload的内部文件列表
    }
  }
};

// 加载个人信息
const loadProfile = async () => {
  const res = await getInfo()
  if (res.code === 200) {
    console.log('loadProfile 获取到的用户信息:', res.data);
    profileForm.realName = res.data.user.realName
    profileForm.phone = res.data.user.phone
    profileForm.email = res.data.user.email
    userStore.userInfo = res.data.user // 直接更新 userInfo，确保包含 avatar
    console.log('loadProfile 后 userStore.userInfo.avatar:', userStore.userInfo.avatar);
  }
}

// 提交个人信息
const submitProfileForm = async () => {
  if (!profileFormRef.value) return
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await updateProfile(profileForm)
      if (res.code === 200) {
        ElMessage.success('个人信息更新成功')
        loadProfile()
        emit('success')
      } else {
        ElMessage.error(res.msg || '个人信息更新失败')
      }
    }
  })
}

// 重置个人信息表单
const resetProfileForm = () => {
  loadProfile() // 重新加载原始信息
}

// 提交密码修改
const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await updatePassword(passwordForm.oldPassword, passwordForm.newPassword)
      if (res.code === 200) {
        ElMessage.success('密码修改成功，请重新登录')
        emit('success')
        userStore.logout()
      } else {
        ElMessage.error(res.msg || '密码修改失败')
      }
    }
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.resetFields()
}

// 头像上传成功回调 (调整以适应手动上传的返回值)
const handleAvatarSuccess: UploadProps['onSuccess'] = (response: any) => {
  console.log('头像上传成功响应:', response);
  if (response.code === 200) {
    ElMessage.success('头像上传成功')
    userStore.userInfo.avatar = response.data.avatarUrl; // 更新store中的头像URL
    console.log('handleAvatarSuccess 后 userStore.userInfo.avatar (直接更新):', userStore.userInfo.avatar);
    loadProfile() // 重新加载用户最新信息
    // emit('success') // 暂时注释掉，方便调试
  } else {
    ElMessage.error(response.msg || '头像上传失败')
  }
}

// 头像上传前校验 (rawFile现在直接来自fileToUpload)
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) => {
  if (!['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)) {
    ElMessage.error('头像图片只能是 JPG/PNG/GIF 格式!')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

onMounted(() => {
  loadProfile()
})
</script>

<style scoped lang="scss">
.profile-container {
  padding: 20px;
}
.profile-form,
.password-form {
  max-width: 400px;
  padding: 20px 0;
}
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    border-radius: 6px;
    object-fit: cover;
  }
  .tip {
    margin-top: 10px;
    font-size: 14px;
    color: #909399;
  }
}
</style>
